<template>
  <el-form
    ref="form"
    :rules="ruleCustom"
    :model="form"
  >
    <el-form-item
      prop="name"
      label="唯一标识"
    >
      <el-input
        v-model="form.name"
        placeholder="请输入1-10位字符"
        :maxlength="10"
      />
    </el-form-item>
    <el-form-item
      prop="display_name"
      label="角色名称"
    >
      <el-input
        v-model="form.display_name"
        placeholder="请输入角色名称"
      />
    </el-form-item>
    <el-form-item
      prop="description"
      label="描述"
    >
      <el-input
        v-model="form.description"
        placeholder="角色描述"
        type="textarea"
        maxlength="255"
        show-word-limit
      />
    </el-form-item>
    <p>权限</p>
    <el-tree
      @check="permission_change"
      :default-checked-keys="form.permissions"
      node-key="id"
      :props="tree_props"
      :data="permission_tree"
      show-checkbox
    >
    </el-tree>
    <el-form-item class="text-center">
            <el-button @click="submit('form')" :loading="btnload">提交</el-button>
        </el-form-item>
  </el-form>
</template>

<script>
import { permissionTree, createRole } from "@/api";
export default {
  data() {
    return {
      permission_tree: [],
      btnload:false,
      tree_props: {
        label: "display_name",
        children: "children"
      },
      form: {
        name: "",
        display_name: "",
        description: "",
        permissions: []
      },
      ruleCustom: {
        name: [
          { required: true, message: "唯一标识不能为空", trigger: "blur" },
          { max: 10, min: 1, message: "唯一标识为1到10位字符", trigger: "blur" }
        ],
        display_name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        description: [
          {
            max: 10,
            message: "描述至多100位字符",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    permissionTree(
      res => {
        this.permission_tree = res.data.tree;
      },
      err => {}
    );
  },
  methods: {
    permission_change(data, checked) {
      this.form.permissions = checked.checkedKeys;
    },
    submit(data) {
      this.$submit(this, data, () => {
        this.btnload = true;
        createRole(
          this.form,
          () => {
            this.btnload = false;
            this.$emit("close", true);
          },
          () => {
            this.btnload = false;
          }
        );
      });
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
